package shg.book.read
{
	import com.hurlant.crypto.Crypto;
	import com.hurlant.crypto.symmetric.ICipher;
	
	import flash.display.NativeWindowSystemChrome;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.controls.HTML;
	import mx.controls.Image;
	import mx.controls.SWFLoader;
	import mx.controls.Text;
	
	import shg.book.database.ConnectionDatabase;
	import shg.book.size.BookData;
	import shg.book.socket.SocketDate;
	import shg.book.view.Adversit;
	import shg.book.view.ConverPage;
	import shg.book.view.ReadTextBook;
	import shg.book.view.TextPage;
	
	import spark.components.Window;

	public class ReadTextBookAction
	{
		static public var showBook:ReadTextBook;
		//样式字符串
		static public var styleText:String;
		//页面字节数组
		static public var pageArray:ArrayCollection;
		//正文部分的数组
		static public var contentArray:ByteArray=new ByteArray();
		//页面背景
		static public var pagebg:String="assets/page/bg/bg4.gif";
		//正文开始插入位置
		private var index:Number=2;
		//封面
		private var converThree:ByteArray;
		private var converFour:ByteArray;
		//广告页数添加的起始位置
		private var adversitCoumt:Number=1;
		
		static private var time:Number=0;
		//当前打开这本书的名称，当用户关闭这本书的时候需要根据这个名称去数据库端更新数据
		public var name:String;
		private var page:TextPage;
		
		public function ReadTextBookAction()
		{
		}
		/**
		 * 选择加载的文件
		 * */
		public function selectFile(event:Event=null):void{
			//保存文件路劲
			if(event!=null)
				BookData.filePath=event.currentTarget.nativePath.toString();
			trace(BookData.filePath);
			var request:URLRequest = new URLRequest(BookData.filePath);
			var loader:URLStream = new URLStream();
			loader.addEventListener(Event.COMPLETE, loaderFile);
			loader.load(request);
		}
		/**
		 * 加载本地文件
		 * 0000000000免费纯文本
		 * 0000000001收费纯文本
		 * 0000000010免费HTML
		 * 0000000011收费HTML
		 * 0000000020免费漫画
		 * 0000000021收费漫画
		 * */
		private function loaderFile(event:Event):void{
			var contentByte:ByteArray=new ByteArray();
			var fileStream:URLStream=event.currentTarget as URLStream;
			//文本内容
			fileStream.readBytes(contentByte);
			fileStream.close();
			var copyRight:String;//版本信息
			try{
				contentByte.position=0;
				copyRight=contentByte.readUTFBytes(10);
				if(copyRight=="0000000000"){//免费纯文本
					decrypt(contentByte);
				}else if(copyRight=="0000000001"){//收费纯文本
					
				}else if(copyRight=="0000000010"){//免费HTML
					
				}else if(copyRight=="0000000011"){//收费HTML
					
				}else if(copyRight=="0000000020"){//免费漫画
					
				}else if(copyRight=="0000000021"){//收费漫画
					
				}else{
					trace("文本内容已经被篡改！");
				}
			}catch(error:Error){
				trace("读取文件出现异常："+error.toString());
			}
		}
		/**
		 * 免费书籍解密
		 * */
		private function decrypt(byte:ByteArray):void{
			//读取键值
			var key:ByteArray = new ByteArray();
			byte.readBytes(key, 0, BookData.AES_LENGTH); 
			//读取加密字符的长度
			var lenght:Number=Number(byte.readUTFBytes(BookData.LENGTH));
			//读取密文
			var encryptedBytes:ByteArray = new ByteArray();
			byte.readBytes(encryptedBytes,0,lenght); 
			try{
				var aes:ICipher = Crypto.getCipher("aes-ecb", key, Crypto.getPad("pkcs5"));
				aes.decrypt(encryptedBytes);
			}catch(error:Error){
				trace("解密失败"+error.toString());
			}
			//重新定位
			encryptedBytes.position=0;
			var buffer:String=encryptedBytes.toString();
			BookData.bookID=buffer.substr(0,BookData.BOOK_ID);//获取数据的ID号
			var bookSizeLeng:Number=Number(buffer.substr(BookData.BOOK_ID,BookData.LENGTH));//表示书籍大小的长度
			var bookSizeArray:String=buffer.substr(BookData.BOOK_ID+BookData.LENGTH*1,bookSizeLeng);//书籍大小数组
			var imgLength:Number=Number(buffer.substr(BookData.BOOK_ID+BookData.LENGTH*1+bookSizeLeng,BookData.LENGTH));	//图片数组长度
			var imgArray:String=buffer.substr(BookData.BOOK_ID+BookData.LENGTH*2+bookSizeLeng,imgLength);		//封面字节数组
			var styleLength:Number=Number( buffer.substr(BookData.BOOK_ID+BookData.LENGTH*2+bookSizeLeng+imgLength,BookData.LENGTH));	//样子字节数组长度
			var styleArray:String=buffer.substr(BookData.BOOK_ID+BookData.LENGTH*3+bookSizeLeng+imgLength,styleLength);	//样式字节数组
			var pageLength:Number=Number(buffer.substr(BookData.BOOK_ID+BookData.LENGTH*3+bookSizeLeng+imgLength+styleLength,BookData.LENGTH));	//分页字节数组长度
			var pageText:String=buffer.substr(BookData.BOOK_ID+BookData.LENGTH*4+bookSizeLeng+imgLength+styleLength,pageLength);	//分页字节数组
			
			BookData.BOOK_WIDTH=Number(bookSizeArray.split("&")[0]);
			BookData.BOOK_HEIGTH=Number(bookSizeArray.split("&")[1]);
			//打开书籍和广告信息
			openBook(bookSizeArray,imgArray,byte,styleArray,pageText);
		}
		private function openBook(bookSizeArray:String,imgArray:String,contentByte:ByteArray,styleArray:String,pageText:String):void{
			//把书籍显示出来
			if(showBook!=null)
				showBook.closeWin();
			showBook=null;
			showBook=new ReadTextBook();
			showBook.width =BookData.SCREEN_X;
			showBook.height = BookData.SCREEN_Y;
			showBook._width =BookData.BOOK_WIDTH;
			showBook._height = BookData.BOOK_HEIGTH;
			showBook.systemChrome=NativeWindowSystemChrome.NONE;
			showBook.transparent=true;
			showBook.showStatusBar=false;
			showBook.open();
			showBook.book.width=BookData.BOOK_WIDTH;
			showBook.book.height=BookData.BOOK_HEIGTH;
			showBook.bookPath=BookData.filePath;
			showBook.ID=name;
			
			var connectdb:ConnectionDatabase =new ConnectionDatabase();
			//connectdb.selectForID(name,showBook);
			//封面一
			var byte:ByteArray=new ByteArray();
			contentByte.readBytes(byte,0,Number(imgArray.split("&")[0]));
			showBook.converFirst=byte;
			//封面二
			byte=new ByteArray();
			contentByte.readBytes(byte,0,Number(imgArray.split("&")[1]));
			var converTwo:ConverPage=new ConverPage();
			addConver(byte,converTwo);
			//封面三
			converThree=new ByteArray();
			contentByte.readBytes(converThree,0,Number(imgArray.split("&")[2]));
			var converPage:ConverPage=new ConverPage();
			addConver(converThree,converPage);
			//封面四
			converFour=new ByteArray();
			contentByte.readBytes(converFour,0,Number(imgArray.split("&")[3]));
			showBook.converLast=converFour;
			//添加广告信息
			addAdversit();
			//添加页面
			styleText=styleArray;
			pageArray=new ArrayCollection(pageText.split("&"));
			//这个数组是用于存储当前已经加载的页面的，如0:1232  null 1232:2322 中间的空表示第二页还没有加载，这数组的大小总是大于前面的数组
			//curentPage=new ArrayCollection(new Array(pageArray.length));
			//最后一个数组里面的数据就是写入文件的时候最后一页的数据，这一页的数据的posiction+最后一页的大小就是这本书正文的大小
			var contentSize:Number=Number(pageArray[pageArray.length-1].toString().split(":")[0])
				+Number(pageArray[pageArray.length-1].toString().split(":")[1]);
			contentByte.readBytes(contentArray,0,contentSize);
			//获取文本总长度（除了批注部分）
			showBook.contextLength=contentByte.position;
			//下面是批注部分
			showBook.annotaction = contentByte.readUTFBytes(contentByte.bytesAvailable);
			showBook.readTextBookAction=this;
			//buidTextPage(null);
		}
		public function buidTextPage(event:Event):void{
			var arr:Array = new Array(pageArray.length);
			arr.forEach(addEachPage);
		}
		private function addEachPage(element:*, index:int, arr:Array):void{
			page=new TextPage();
			page.readTextBook=showBook;
			page.pageIndex=index;
			page.readTextBookAction=this;
			arr.push(page);
			arr.shift();
			if((index+1)==pageArray.length){
				var cover:Array=showBook.book.content
				arr.unshift(cover[0]);
				if((index+1)%2!=0){
					var endPage:TextPage=new TextPage();
					endPage.readTextBook=showBook;
					endPage.pageIndex=index;
					endPage.readTextBookAction=this;
					arr.push(endPage);
				}
				arr.push(cover[1]);
				showBook.book.content=arr;
			}
			trace("第"+index+"页");
		}
		/**
		 * 这是里添加数据
		 * */
		private function addAdversit():void{
			try{
				for(var i:int=0;i<SocketDate.adversitPath.length;i++){
					var adversit:Adversit=new Adversit();
					adversit.readTextBook=showBook;
					adversit.index=adversitCoumt;
					adversit.swfPath=String(SocketDate.adversitPath.getItemAt(i));
					addAdversitPage(adversit);
					index=i+3;
				}
			}catch(error:Error){
				trace("加载广告出现异常："+error.toString());
			}
		}
		/**
		 * 添加书籍页面内容
		 * 这里将会读取剩下的所有字节数组
		 * 包括注解部分，因为字节部分都是文字内容所有没什么后患
		 * 这里是首次打开书籍，只需要打开20页即可，如果小于等于20页就打开所有页
		 * 其次是pageIndex表示的是上次你打开的页数，
		 * 第一步：先计算应该打开从哪一页到哪一页
		 * 
		private function updatePage():void{
			//首先判断这本书有多少页
			var i:int=0
			var pageSize:Number=0;
			//如果这本书小于等于20页的时候就加载所有的书籍
			if(pageArray.length<=20){
				for(;i<pageArray.length;i++){
					pageSize=Number(pageArray[i].toString().split(":")[1]);
					makePage(pageSize,i);
				}
			}else{
				var startIndex:Number=0;
				var endIndex:Number=0;
				if(showBook.index-10>=0 && showBook.index+10<=pageArray.length){
					//这种情况是index这一页是在中央加、减10都不会越界
					startIndex=showBook.index-10;
					endIndex=showBook.index+10;
				}else if(showBook.index-10>=0 && showBook.index+10>pageArray.length){
					//这种情况是右边越界
					startIndex=pageArray.length-20;
					endIndex=pageArray.length;//指向最后那个
					//这个时候打开也就不是中心页了
					showBook.openIndex=showBook.index;
				}else if(showBook.index-10<0 && showBook.index+10<pageArray.length){
					//这种情况就是左边越界
					startIndex=0;
					endIndex=20;
					showBook.openIndex=showBook.index;
				}
				for( ; startIndex < endIndex ; startIndex++){
					pageSize=Number(pageArray[startIndex].toString().split(":")[1]);
					makePage(pageSize,startIndex);
				}
			}
			if(i%2!=0){
				var endPage:TextPage=new TextPage();
				addPage(endPage);
			}
			//这个将当前对象赋值给showBook,稍后翻页的时候读取数据需要用到这个对象的很多数据
			showBook.readTextBookAction=this;
			//一分钟后可以删除广告页
			var time:Timer=new Timer(10000,2);
			time.addEventListener(TimerEvent.TIMER,tearOut);
			time.start();
		}*/
		/**
		 * 组装成一个页面
		 **/ 
		 private function makePage(pageSize:Number,index:Number):void{
			//首先将这一页删除，再保持一些标书进入该项
			 pageArray.removeItemAt(index);
			 pageArray.addItemAt(null,index);
			 
			var page:TextPage=new TextPage();
			page.readTextBook=showBook;
			page.pageIndex=index;
			TextPage.imgPath=pagebg;
			var pageContent:String=contentArray.readUTFBytes(pageSize);
			page.textFild=getTextFild(pageContent);
			addPage(page);
		}
		/**
		 * 撕出广告页
		 * */
		private function tearOut(event:TimerEvent):void{
			if(time>0)
				ReadBookDate.TEAR_OUT_ADVERSIT=true;
			time++;
		}
		/**
		 * 构造TextFild显示器
		 * */
		public function getTextFild(pageContent:String):TextField{
			var textField:TextField=new TextField();
			textField.wordWrap=true;						//允许自动换行
			textField.width=(BookData.BOOK_WIDTH/2)-(BookData.BORDER_MARGIN*2);	//每行文本的显示宽度
			textField.height=BookData.BOOK_HEIGTH-(BookData.BORDER_MARGIN*2);
			//给文本添加样式
			var format:TextFormat = new TextFormat();
			format.font = styleText.split("&")[0];
			format.color = styleText.split("&")[1];
			format.size = styleText.split("&")[2];
			format.bold= styleText.split("&")[3];
			//设置文本样式
			textField.defaultTextFormat=format;
			textField.text=pageContent;
			return textField
		}
		/**
		 * 添加页面
		 * */
		private function addPage(page:TextPage):void{
			var content:Array = showBook.book.content;
			var contentPage:ArrayCollection=new ArrayCollection(content);
			contentPage.addItemAt(page,contentPage.length-1);
			content=contentPage.toArray();
			showBook.book.content = content;				
		}
		/**
		 * 添加封面
		 * */
		private function addConver(byte:ByteArray,coverPage:ConverPage):void{
			coverPage.converByte=byte;
			var content:Array = showBook.book.content;
			content.push(coverPage);
			showBook.book.content = content;				
		}
		/**
		 * 添加广告页
		 * */
		private function addAdversitPage(adversit:Adversit):void{
			var content:Array = showBook.book.content;
			var bookPage:ArrayCollection=new ArrayCollection(content);
			bookPage.addItemAt(adversit,adversitCoumt);
			content=bookPage.toArray(); 
			showBook.book.content = content;	
			adversitCoumt++;
			showBook.adversitCoumt=adversitCoumt-1;
		}
	}
}